package com.ajouroid.smartcoworker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private HorizontalScrollView _scroll;

	private ProgressBar ppt_progbar;
	private ProgressBar edit_progbar;

	LinearLayout pptLayout;
	LinearLayout editLayout;
	LinearLayout handle;

	Point screenSize;

	private ViewGroup _layout;
	// private int IMAGE_COUNT = 0;
	private int ppt_cur_Index = 0;
	private int edit_cur_Index = 0;

	private static final int ADDFRIENDS_ACTIVITY = 0;

	private CustomImageView pptView;
	private CustomImageView temp;
	private TextView ppt_statusText;
	private CustomImageView editView;
	private TextView edit_statusText;
	private TextView tv_myid;
	private TextView modecheckText;
	private ImageView iv_notify_msg;
	private ImageView iv_myprofile;
	private ImageButton btn_add_member;
	private ImageButton dynamic_imgbtn;
	private TextView dynamic_txtview;
	private LinearLayout dynamic_layout;
	private FrameLayout dynamic_frame;
	private ProgressBar dynamic_progbar;
	private int member_count = 0;

	private Button btn_ppt_prev;
	private Button btn_ppt_next;
	private Button btn_edit_prev;
	private Button btn_edit_next;
	private ImageButton btn_attribute;
	private ImageButton btn_eraser;
	private CheckBox modeCheckBox;
	private int select_view = 0;

	private EditText et_chatMsg;
	private ListView lv_msgList;
	private Button btn_sendMsg;
	private ArrayList<User> mem_list;
	private ArrayList<User> tmp_list;
	private ArrayList<User> addition_list;
	private ArrayList<String> member_id_list;
	private ArrayList<ChatMessage> msgList;
	Animation myFadeInAnimation;
	ChatAdapter chatAdapter;
	ProgressDialog uploadDialog;
	public boolean owner = false;

	// 뒤로 두번눌러 종료 구현
	private boolean m_bFlag = false;
	private Handler mBackClickHandler;

	private Handler mSearchImgHandler;
	private Handler mSearchUserHandler;

	String myId = null;
	Team team = null;
	Slide slide = null;
	LinearLayout all;
	LinearLayout list;
	WrappingSlidingDrawer drawer;

	ImageAdapter ia;
	Integer a;

	HashMap<String, Bitmap> profile_img_factory;

	private final String TAG = "MainActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_main);

		mBackClickHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					m_bFlag = false;
				}
			}
		};

		ppt_progbar = (ProgressBar) findViewById(R.id.pm_ppt_progbar);
		edit_progbar = (ProgressBar) findViewById(R.id.pm_edit_progbar);
		pptView = (CustomImageView) findViewById(R.id.pm_ppt_view);
		pptView.setViewType(1);

		ppt_statusText = (TextView) findViewById(R.id.pm_ppt_status_text);

		editView = (CustomImageView) findViewById(R.id.pm_edit_view);
		editView.setViewType(2);

		edit_statusText = (TextView) findViewById(R.id.pm_edit_status_text);
		modecheckText = (TextView) findViewById(R.id.pm_text_modecheck);

		modeCheckBox = (CheckBox) findViewById(R.id.pm_cb_drawing_mode);
		modeCheckBox.setButtonDrawable(R.drawable.stroke_checkbox);
		modeCheckBox.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (modeCheckBox.isChecked()) {
					editView.setMode(true);
					pptView.setMode(true);
					modecheckText.setText("Drawing");
				} else {
					editView.setMode(false);
					pptView.setMode(false);
					modecheckText.setText("Zooming");
				}
			}
		});

		_scroll = (HorizontalScrollView) findViewById(R.id.pm_scrollview);
		_layout = (ViewGroup) findViewById(R.id.pm_scroll_inner);

		iv_notify_msg = (ImageView) findViewById(R.id.pm_notify_msg);
		iv_notify_msg.setVisibility(View.GONE);
		myFadeInAnimation = AnimationUtils.loadAnimation(MainActivity.this,
				R.drawable.blink);

		btn_add_member = (ImageButton) findViewById(R.id.pm_add_member);
		btn_ppt_prev = (Button) findViewById(R.id.pm_btn_ppt_prev);
		btn_ppt_next = (Button) findViewById(R.id.pm_btn_ppt_next);
		btn_edit_prev = (Button) findViewById(R.id.pm_btn_edit_prev);
		btn_edit_next = (Button) findViewById(R.id.pm_btn_edit_next);
		btn_attribute = (ImageButton) findViewById(R.id.pm_btn_pen_edit);
		btn_eraser = (ImageButton) findViewById(R.id.pm_btn_eraser);
		lv_msgList = (ListView) findViewById(R.id.pm_past_msglist);
		btn_sendMsg = (Button) findViewById(R.id.pm_send_msg);
		et_chatMsg = (EditText) findViewById(R.id.pm_input_msg);
		pptLayout = (LinearLayout) findViewById(R.id.pm_ppt_layout);
		editLayout = (LinearLayout) findViewById(R.id.pm_edit_layout);

		handle = (LinearLayout) findViewById(R.id.pm_handle);

		tv_myid = (TextView) findViewById(R.id.pm_myid);
		iv_myprofile = (ImageView) findViewById(R.id.pm_myprofile);
		screenSize = new Point();
		((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getSize(screenSize);

		all = (LinearLayout) findViewById(R.id.aaaa);
		list = (LinearLayout) findViewById(R.id.listLayout);
		drawer = (WrappingSlidingDrawer) findViewById(R.id.sliding_drawer);
		mem_list = new ArrayList<User>();
		tmp_list = new ArrayList<User>();
		member_id_list = new ArrayList<String>();
		msgList = new ArrayList<ChatMessage>();
		profile_img_factory = new HashMap<String, Bitmap>();

		Intent intent = getIntent();

		if (intent.hasExtra("id")) {
			myId = intent.getStringExtra("id");
			tv_myid.setText(myId);
			// set profile image
			String imgName = intent.getStringExtra("image");
			if (imgName != null && !imgName.equals("null")) {
				GetImageTask imgTask = new GetImageTask(iv_myprofile, null);
				imgTask.execute(myId);
			}
		}

		if (intent.hasExtra("team_info")) {
			String team_info = intent.getStringExtra("team_info");
			team = Team.parseFromString(team_info);

			if (team != null) {
				member_id_list = team.getMembers();
				MemberSearchTask ms_task = new MemberSearchTask();
				ms_task.execute(member_id_list,0);

				slide = new Slide(team.getId(), team.getSlides());
				setPage(1, 0);
				setPage(2, 0);
				// IMAGE_COUNT = slide.size();
				pptView.setData(team.getId(), team.leader, myId, slide.size());
				editView.setData(team.getId(), myId, slide.size());
			} else {
				Log.d(TAG, "Team info didn't arrived");
				finish();
			}
		}

		if (myId.equals(team.leader)) {
			btn_add_member.setOnClickListener(new Add_MemberListener());
		} else {
			btn_add_member.setVisibility(View.GONE);
		}

		registerReceiver(mReceiver, new IntentFilter(
				"edu.ajou.smartcoworker.PUSHMSG"));

	}

	@Override
	public void onResume() {
		super.onResume();

		btn_eraser.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				pptView.setEraser(v);
				editView.setEraser(v);
				// TODO Auto-generated method stub

			}
		});

		handle.setOnTouchListener(new HandleListener());

		btn_ppt_next.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (myId.equals(team.leader))
					showNextImage(1);
			}

		});

		btn_ppt_prev.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (myId.equals(team.leader))
					showPrevImage(1);
			}

		});

		btn_edit_next.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showNextImage(2);
			}

		});

		btn_edit_prev.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showPrevImage(2);
			}

		});

		btn_attribute.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				pptView.setPenAttribute();
				editView.attributeChanged(pptView.getPaint());
			}

		});

		btn_sendMsg.setOnClickListener(new SendMessageListener());
		et_chatMsg.setOnKeyListener(new OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER
						&& KeyEvent.ACTION_DOWN == event.getAction()) {
					String msg = et_chatMsg.getText().toString();

					SendMessageTask task = new SendMessageTask();
					task.execute(msg);

					msgList.add(new ChatMessage(myId, msg));
					chatAdapter.notifyDataSetChanged();

					et_chatMsg.setText("");
					return true;
				}

				return false;
			}
		});

		drawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			public void onDrawerOpened() {
				// TODO Auto-generated method stub
				iv_notify_msg.setVisibility(View.GONE);
				lv_msgList.setSelection(lv_msgList.getChildCount() - 1);
			}
		});

		chatAdapter = new ChatAdapter(this);
		lv_msgList.setAdapter(chatAdapter);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case ADDFRIENDS_ACTIVITY:
			if (resultCode == RESULT_OK) {
				tmp_list = (ArrayList<User>) data.getExtras().getSerializable(
						"add_list");
				for (int i = 0; i < tmp_list.size(); i++) {
					mem_list.add(tmp_list.get(i));
				}
				for (int mem = 0; mem < tmp_list.size(); mem++) {
					creatMemberObj(tmp_list.get(mem));
				}
				// 占쏙옙튼占쏙옙 占쏙옙占쏙옙占십몌옙 占심억옙占쌔댐옙.
				renewMemberObj();
				// 친구 추가 요청 서버로 전송
				ManagementMemberTask addmem_task = new ManagementMemberTask(
						MainActivity.this);
				addmem_task.execute(team.getId(), "add", tmp_list);
			}
		}
	}

	@Override
	public void onDestroy() {
		this.unregisterReceiver(mReceiver);
		LogoutTask task = new LogoutTask();
		task.execute(myId);

		super.onDestroy();
	}

	private class HandleListener implements View.OnTouchListener {
		float sx;
		float sy;

		float screenX;

		float x;
		float y;

		int width = 0;
		int height = 0;

		public boolean onTouch(View arg0, MotionEvent arg1) {

			int barWidth = handle.getWidth();

			x = arg1.getX();
			y = arg1.getY();

			int leftSize;
			LayoutParams pptParams;

			switch (arg1.getAction()) {
			case MotionEvent.ACTION_DOWN:

				sx = x;
				sy = y;

				width = pptLayout.getWidth();
				height = pptLayout.getHeight();

				Log.d("Test", "DOWN: " + sx + ", " + sy);

				break;

			case MotionEvent.ACTION_MOVE:
				Log.d("Test", "MOVE: " + x + ", " + y);

				int dx = (int) (x - sx);

				width += dx;

				pptLayout.setLayoutParams(new LinearLayout.LayoutParams(width,
						height));

				break;

			case MotionEvent.ACTION_UP:
				Log.d("Test", "UP: " + x + ", " + y);

				float rate = (x + handle.getLeft()) / (float) screenSize.x;

				float remainScreenSize = (float) (screenSize.x - handle
						.getWidth());

				int zeroX = 0;
				int maxX = (int) remainScreenSize;
				int shortX = (int) (remainScreenSize * 0.4);
				int longX = (int) (remainScreenSize * 0.6);

				if (rate < 0.2) {
					pptLayout.setLayoutParams(new LinearLayout.LayoutParams(
							zeroX, height));
				} else if (rate < 0.4) {
					pptLayout.setLayoutParams(new LinearLayout.LayoutParams(
							shortX, height));
				} else if (rate > 0.8) {
					pptLayout.setLayoutParams(new LinearLayout.LayoutParams(
							maxX, height));
				} else if (rate > 0.6) {
					pptLayout.setLayoutParams(new LinearLayout.LayoutParams(
							longX, height));
				}

				else if (rate < 0.4) {
					pptLayout.setLayoutParams(new LinearLayout.LayoutParams(
							zeroX, height));
				}

			}
			return true;
		}

	}

	class Add_MemberListener implements OnClickListener {

		public void onClick(View view) {
			// TODO Auto-generated method stub

			Intent intent = new Intent(MainActivity.this,
					AddFriendsActivity.class);
			intent.putExtra("myId", myId);
			intent.putExtra("exist_list", mem_list);
			startActivityForResult(intent, ADDFRIENDS_ACTIVITY);
		}

	}

	class MemClickListener implements OnClickListener {
		User cur_user;
		int cur_pos;
		Bitmap bm_img;
		Drawable cur_img;

		public void onClick(View v) {
			// TODO Auto-generated method stub
			int[] lo = new int[2];
			v.getLocationOnScreen(lo);
			cur_user = (User) v.getTag();
			cur_pos = v.getId();
			int posX = lo[0];
			int halfWidth = (int) (v.getWidth() * 0.5f);
			int screenWith = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
					.getDefaultDisplay().getWidth();
			int halfScreenWidth = (int) (screenWith * 0.5f);
			final int scroll = posX + halfWidth - halfScreenWidth;
			_scroll.post(new Runnable() {
				public void run() {
					_scroll.smoothScrollBy(scroll, 0);
				}
			});

			new Thread(new Runnable() {
				@SuppressWarnings("deprecation")
				@SuppressLint("HandlerLeak")
				public void run() {

					try {
						Bitmap tmp_bm = null;
						HttpGet get = new HttpGet(HttpConnector.getAddress()
								+ "ProfileImage?id=" + cur_user.getId());
						HttpClient client = new DefaultHttpClient();
						HttpResponse resp = client.execute(get);
						tmp_bm = BitmapFactory.decodeStream(resp.getEntity()
								.getContent());
						bm_img = Bitmap.createScaledBitmap(tmp_bm, 130, 150,
								true);
						cur_img = new BitmapDrawable(bm_img);
						mSearchImgHandler.sendMessage(mSearchImgHandler
								.obtainMessage());
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						bm_img = BitmapFactory.decodeResource(getResources(),
								R.drawable.anonymous);
						cur_img = new BitmapDrawable(bm_img);
						mSearchImgHandler.sendMessage(mSearchImgHandler
								.obtainMessage());
					}
				}
			}).start();
			mSearchImgHandler = new Handler() {
				public void handleMessage(android.os.Message msg) {
					new AlertDialog.Builder(MainActivity.this)
							.setTitle(cur_user.getId())
							.setIcon(cur_img)
							.setNegativeButton("Cancel",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int sumthin) {
											dialog.dismiss();
										}
									})
							.setPositiveButton("Delete member",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int sumthin) {

											if (myId.equals(team.leader)) {
												if (cur_user.getId().equals(
														myId)) {
													Toast.makeText(
															getApplicationContext(),
															"Cannot delete yourself",
															Toast.LENGTH_SHORT)
															.show();
												} else if (cur_user.getId()
														.equals(team.leader)) {
													Toast.makeText(
															getApplicationContext(),
															"Cannot delete team leader",
															Toast.LENGTH_SHORT)
															.show();
												} else {
													delMember(cur_pos,
															cur_user.getId());
												}
											} else {
												Toast.makeText(
														getApplicationContext(),
														"You are not team leader!",
														Toast.LENGTH_SHORT)
														.show();
											}
											dialog.dismiss();
										}
									}).show();
				};
			};
		}

	}

	class MemberSearchTask extends AsyncTask<Object, Void, Integer> {
		HttpConnector conn;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

			owner = true;
		}

		@Override
		protected Integer doInBackground(Object... params) {

			conn = new HttpConnector();
			Map<String, String> msgs = new HashMap<String, String>();
			@SuppressWarnings("unchecked")
			ArrayList<String> arr_list = (ArrayList<String>) params[0];
			int search_mode = (Integer) params[1];

			for (int i = 0; i < arr_list.size(); i++) {
				msgs.put("id", arr_list.get(i));
				msgs.put("exact", "true");

				try {
					String ret = conn.get("FindMember", msgs);
					JSONObject obj = new JSONObject(ret);
					JSONArray arr = obj.getJSONArray("members");
					JSONObject ob = arr.getJSONObject(0);

					String id = ob.getString("id");
					String name = ob.getString("name");
					String email = ob.getString("email");
					String photo = ob.getString("image");

					User ui = new User(id, name, email, photo);
					mem_list.add(ui);
					if(search_mode == 1){
						addition_list.add(ui);
					}
					
				} catch (JSONException e) {

					e.printStackTrace();
				} catch (ClientProtocolException e) {

					e.printStackTrace();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
			return search_mode;
		}

		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result == 0){
				for (int i = 0; i < mem_list.size(); i++) {
					creatMemberObj(mem_list.get(i));
				}
			}
			else if(result == 1){
				for (int i = 0; i < addition_list.size(); i++) {
					creatMemberObj(addition_list.get(i));
				}
			}
			renewMemberObj();
		}
	}
	
	
	class ManagementMemberTask extends AsyncTask<Object, String, Boolean> {
		HttpConnector conn;
		Context mCtx;

		public ManagementMemberTask(Context context) {
			mCtx = context;
		}

		@Override
		protected void onPreExecute() {
			conn = new HttpConnector();

			uploadDialog = new ProgressDialog(mCtx);
			uploadDialog.setTitle("Wait please...");
			uploadDialog.setCancelable(false);
			uploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

			uploadDialog.show();

			owner = true;

			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			uploadDialog.setMessage(values[0] + " Member...");
		}

		@SuppressWarnings("unchecked")
		@Override
		protected Boolean doInBackground(Object... params) {
			Map<String, String> msgs = new HashMap<String, String>();
			String team_id = (String) params[0];
			String mode = (String) params[1];
			publishProgress(mode);
			ArrayList<User> arr_list;
			String del_id;

			msgs.put("id", team_id);
			msgs.put("action", mode);

			if (mode.equals("add")) {
				arr_list = (ArrayList<User>) params[2];
				for (int i = 0; i < arr_list.size(); i++) {
					msgs.put("member_id", arr_list.get(i).getId());
				}
			} else {
				del_id = (String) params[2];
				msgs.put("member_id", del_id);
			}

			try {
				String ret = conn.get("TeamAction", msgs);
				JSONObject obj = new JSONObject(ret);
				String re_code = obj.getString("result");
				if (re_code.equals("ok")) {
					return true;
				} else {
					return false;
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			uploadDialog.dismiss();
			if (result) {
				Toast.makeText(getApplicationContext(), "Success!!",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), "Fail!!",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	class SendActionTask extends AsyncTask<String, Void, Void> {
		HttpConnector conn;
		Context mCtx;

		public SendActionTask(Context context) {
			context = mCtx;
		}

		@Override
		protected void onPreExecute() {
			conn = new HttpConnector();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			Map<String, String> msgs = new HashMap<String, String>();
			msgs.put("team_id", params[0]);
			msgs.put("actor", params[1]);
			msgs.put("action", params[2]);

			conn.post("Action", msgs);
			return null;
		}

	}

	class LogoutTask extends AsyncTask<String, Void, Void> {
		HttpConnector conn;

		@Override
		protected Void doInBackground(String... params) {
			conn = new HttpConnector();
			Map<String, String> msgs = new HashMap<String, String>();

			msgs.put("id", params[0]);

			try {
				conn.get("Logout", msgs);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

	}

	private class SendMessageListener implements OnClickListener {

		public void onClick(View v) {
			String msg = et_chatMsg.getText().toString();

			SendMessageTask task = new SendMessageTask();
			task.execute(msg);

			msgList.add(new ChatMessage(myId, msg));
			chatAdapter.notifyDataSetChanged();

			et_chatMsg.setText("");
		}

	}

	private class SendMessageTask extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... arg0) {
			try {
				HttpConnector conn = new HttpConnector();

				Map<String, String> msg = new HashMap<String, String>();

				msg.put("team_id", team.getId());
				msg.put("actor", myId);

				JSONObject obj = new JSONObject();

				obj.put("id", myId);

				obj.put("message", arg0[0]);

				String jsonMessage = obj.toString();
				msg.put("action", jsonMessage);

				conn.post("Action", msg);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			super.onPostExecute(result);
		}
	}

	public void shot(CustomImageView v) {
		// select_view = select;
		temp = v;

		all.setVisibility(View.INVISIBLE);
		drawer.setVisibility(View.INVISIBLE);
		list.setVisibility(View.VISIBLE);

		Gallery gv = (Gallery) findViewById(R.id.ImgGridView);
		WindowManager w = getWindowManager();
		Display d = w.getDefaultDisplay();
		int asdf = d.getHeight() / 2;
		ia = new ImageAdapter(this);
		gv.setAdapter(ia);
		gv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				list.setVisibility(View.INVISIBLE);

				all.setVisibility(View.VISIBLE);
				drawer.setVisibility(View.VISIBLE);
				if (temp.getId() == R.id.pm_ppt_view) {
					setPage(1, a);
					ppt_cur_Index = a;
					SendActionTask task = new SendActionTask(MainActivity.this);
					task.execute(team.getId(), myId, "{ \"moveto\":\"" + ppt_cur_Index
							+ "\" }");
				} else if (temp.getId() == R.id.pm_edit_view) {
					setPage(2, a);
					edit_cur_Index = a;
				}

			}
		});

	}

	public class ImageAdapter extends BaseAdapter {
		private Context mContext;

		ImageAdapter(Context c) {
			mContext = c;
		}

		public final void callImageViewer(int selectedIndex) {
			slide.setPage(mContext, pptView, ppt_progbar, selectedIndex);
		}

		public boolean deleteSelected(int sIndex) {
			return true;
		}

		public int getCount() {
			return slide.files.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			ImageView imageView = null;
			ImageView img2 = null;
			TextView listtxt = null;
			LinearLayout a;
			LinearLayout b;
			TextView listtxt2 = null;
			ProgressBar list_prog;
			ProgressBar list_prog2;

			View v;

			if (convertView == null) {
				LayoutInflater li = getLayoutInflater();
				v = li.inflate(R.layout.icon, null);
				v.setPadding(0, 20, 0, 20);
				// v.setLayoutParams(new LinearLayout.LayoutParams(400,400));
				imageView = (ImageView) v.findViewById(R.id.img1);
				imageView.setPadding(50, 50, 50, 50);
				a = (LinearLayout) v.findViewById(R.id.llist1);
				b = (LinearLayout) v.findViewById(R.id.llist2);
				a.setVisibility(View.INVISIBLE);
				listtxt = (TextView) v.findViewById(R.id.listtxt);
				// list_prog2 = (ProgressBar)v.findViewById(R.id.list_progbar2);
				// list_prog.setVisibility(View.GONE);
				// list_prog2.setVisibility(View.GONE);
				if (position > 6) {
					for (int i = 0; i < position - 3; i++) {
						slide.pages[i] = null;
					}
				}
				if (position + 3 < slide.files.size()) {
					if (slide.pages[position + 3] != null) {
						for (int i = position + 3; i < slide.files.size(); i++) {
							slide.pages[i] = null;
						}
					}
				}
				slide.downall(MainActivity.this, position, imageView, listtxt,
						a, b);// ,list_prog2);

			} else {

				v = convertView;
			}

			return v;
		}

	}

	class ChatAdapter extends ArrayAdapter<ChatMessage> {
		private int rsrc;

		public ChatAdapter(Context ctx) {
			super(ctx, R.layout.row_chatmessage, R.id.chat_row_message, msgList);
			this.rsrc = R.layout.row_chatmessage;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
			}
			ChatMessage message = msgList.get(position);
			if (message != null) {
				((ImageView) v.findViewById(R.id.chat_row_profile))
						.setImageBitmap(profile_img_factory.get(message.getId()));
				((TextView) v.findViewById(R.id.chat_row_id)).setText(message
						.getId());
				((TextView) v.findViewById(R.id.chat_row_message))
						.setText(message.getMessage());
			}

			return v;
		}
	}

	public boolean onKeyDown(int KeyCode, KeyEvent event) {
		super.onKeyDown(KeyCode, event);

		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (KeyCode) {
			case KeyEvent.KEYCODE_BACK: // `뒤로` 키와 같은 기능을 한다.
				if (!m_bFlag) {
					Toast.makeText(getApplicationContext(),
							"'뒤로'버튼을 한번 더 누르시면 종료됩니다", Toast.LENGTH_SHORT)
							.show();
					m_bFlag = true;
					mBackClickHandler.sendEmptyMessageDelayed(0, 2000);

					return false;
				} else {
					
					if(!myId.equals(team.leader)){
						ManagementMemberTask delmem_task = new ManagementMemberTask(
							MainActivity.this);
						delmem_task.execute(team.getId(), "reject", myId);
					}
					
					DeleteCache del = new DeleteCache();
					del.clearCache(this);
					finish();
				}
			}
		}

		return false;
	}

	private void setPage(int type, int index) {
		if (type == 1) {
			slide.setPage(this, pptView, ppt_progbar, index);
			ppt_statusText.setText(String.format("%d/%d", index + 1,
					slide.size()));
		} else if (type == 2) {
			slide.setPage(this, editView, edit_progbar, index);
			edit_statusText.setText(String.format("%d/%d", index + 1,
					slide.size()));
		}
	}

	private void showPrevImage(int type) {
		if (type == 1) {
			ppt_cur_Index = (ppt_cur_Index - 1) % slide.size();

			if (ppt_cur_Index < 0)
				ppt_cur_Index = slide.size() - 1;

			setPage(1, ppt_cur_Index);

			SendActionTask task = new SendActionTask(MainActivity.this);
			task.execute(team.getId(), myId, "{ \"moveto\":\"" + ppt_cur_Index
					+ "\" }");
		} else if (type == 2) {
			edit_cur_Index = (edit_cur_Index - 1) % slide.size();
			if (edit_cur_Index < 0)
				edit_cur_Index = slide.size() - 1;
			setPage(2, edit_cur_Index);
		}
	}

	private void showNextImage(int type) {
		if (type == 1) {
			ppt_cur_Index = (ppt_cur_Index + 1) % slide.size();
			setPage(1, ppt_cur_Index);

			SendActionTask task = new SendActionTask(MainActivity.this);
			task.execute(team.getId(), myId, "{ \"moveto\":\"" + ppt_cur_Index
					+ "\" }");
		} else if (type == 2) {
			edit_cur_Index = (edit_cur_Index + 1) % slide.size();
			setPage(2, edit_cur_Index);

		}
	}

	private void delMember(int del_pos, String del_id) {
		if (member_count > 0) {
			_layout.removeViewAt(del_pos);
			mem_list.remove(del_pos);
			profile_img_factory.remove(del_id);
			renewMemberObj();

			ManagementMemberTask delmem_task = new ManagementMemberTask(
					MainActivity.this);
			delmem_task.execute(team.getId(), "reject", del_id);
			// 친구 삭제 요청 서버로 전송

		} else {
			Toast.makeText(getApplicationContext(), "not have deleting member",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void renewMemberObj() {
		member_count = _layout.getChildCount(); // member_count 갱신
		for (int i = 0; i < member_count; i++) {
			View v = _layout.getChildAt(i);
			if (v.getClass() != LinearLayout.class)
				return;
			v.setId(i);
			v.setTag(mem_list.get(i));
			v.setOnClickListener(new MemClickListener());
		}
	}
	
	private void creatMemberObj(User _user) {
		dynamic_layout = new LinearLayout(MainActivity.this);
		dynamic_layout.setOrientation(LinearLayout.VERTICAL);
		LinearLayout.LayoutParams linearParam;
		linearParam = new LinearLayout.LayoutParams(
				new LinearLayout.LayoutParams(80, 100));
		linearParam.setMargins(0, 0, 15, 0);
		dynamic_frame = new FrameLayout(MainActivity.this);

		dynamic_layout.setLayoutParams(linearParam);
		dynamic_frame.setLayoutParams(new LinearLayout.LayoutParams(80, 80));
		dynamic_progbar = new ProgressBar(MainActivity.this, null,
				android.R.attr.progressBarStyle);

		dynamic_imgbtn = new ImageButton(MainActivity.this);
		dynamic_imgbtn.setLayoutParams(new LinearLayout.LayoutParams(80, 80));
		dynamic_txtview = new TextView(MainActivity.this);

		dynamic_layout.setClickable(true);
		dynamic_imgbtn.setClickable(false);
		dynamic_txtview.setClickable(false);
		dynamic_txtview.setLayoutParams(new LinearLayout.LayoutParams(80, 20));
		dynamic_txtview.setText(_user.getId());
		dynamic_txtview.setGravity(Gravity.CENTER);
		dynamic_frame.addView(dynamic_progbar);
		dynamic_frame.addView(dynamic_imgbtn);
		dynamic_layout.addView(dynamic_frame);
		dynamic_layout.addView(dynamic_txtview);

		_layout.addView(dynamic_layout);

		if (_user.getPhoto() != null && !_user.getPhoto().equals("null")) {
			dynamic_imgbtn.setVisibility(View.GONE);
			dynamic_progbar.setVisibility(View.VISIBLE);
			GetImageTask imgTask = new GetImageTask(dynamic_imgbtn,
					dynamic_progbar, _user.getId(), profile_img_factory);
			imgTask.execute(_user.getId());
		} else {
			dynamic_progbar.setVisibility(View.GONE);
			dynamic_imgbtn.setBackgroundResource(R.drawable.anonymous);
		}
	}

	BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			String type = arg1.getStringExtra("type");
			String msg = arg1.getStringExtra("content");

			try {
				JSONObject obj = new JSONObject(msg);

				if (type.equals("team_info")) {
					if (obj.get("action").equals("closed")) {
						new AlertDialog.Builder(MainActivity.this)
								.setTitle("Team leader has left SmartCoworker")
								.setMessage(
										"When you click on the Confirm button, \nSmartCoworker will be terminated.")
								.setPositiveButton("Confirm",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												finish();
											}
										}).show();
					}
				} else if (type.equals("action")) {
					if (obj.has("moveto")) {
						int moveTo = obj.getInt("moveto");
						setPage(1, moveTo);
					} else if (obj.has("message")) {
						String id = obj.getString("id");
						String chatMsg = obj.getString("message");
						chatMsg = new String(chatMsg.getBytes("8859_1"),"utf_8");
						ChatMessage newMessage = new ChatMessage(id, chatMsg);
						msgList.add(newMessage);
						chatAdapter.notifyDataSetChanged();
						lv_msgList.setSelection(lv_msgList.getChildCount() - 1);
						if (!id.equals(myId)) {
							iv_notify_msg.setVisibility(View.VISIBLE);
							iv_notify_msg.startAnimation(myFadeInAnimation);
						}
					} else if (obj.has("point")) {
						int page = obj.getInt("page");
						int color = 0xFF000000;
						if (obj.has("color")) {
							color = obj.getInt("color");
						}
						int pen_width = 5;
						if (obj.has("thick")) {
							pen_width = obj.getInt("thick");
						}
						int pen_style = 0;
						if (obj.has("style")) {
							pen_style = obj.getInt("style");
						}
						int pen_eraser = 0;
						if (obj.has("eraser")) {
							pen_eraser = obj.getInt("eraser");
						}
						int pen_type = 0;
						if (obj.has("type")) {
							pen_type = obj.getInt("type");
						}
						int width = obj.getInt("width");
						int height = obj.getInt("height");
						JSONArray pts = obj.getJSONArray("point");
						if (pts.length() != 0) {
							float x;
							float y;
							JSONArray arr;

							arr = pts.getJSONArray(0);
							x = (float) arr.getDouble(0);
							y = (float) arr.getDouble(1);

							PathList pl = new PathList(width, height);

							pl.setcolor(color);
							pl.setthick(pen_width);
							pl.setStyle(pen_style);
							pl.setType(pen_type);
							pl.setEraser(pen_eraser);

							pl.addExact(new PointF(x, y));

							for (int i = 1; i < pts.length(); i++) {
								arr = pts.getJSONArray(i);
								x = (float) arr.getDouble(0);
								y = (float) arr.getDouble(1);
								pl.addExact(new PointF(x, y));
							}
							pptView.addPath(pl, page);
							editView.addPath(pl, page);
						}
					}
					
					else if(obj.get("action").equals("newMember")){

						if(!myId.equals(team.leader)){
							JSONArray arr_obj = obj.getJSONArray("members");
							ArrayList<String> temp_id_list = new ArrayList<String>();
							for(int i=0; i<arr_obj.length(); i++){
								temp_id_list.add(arr_obj.getString(i));
							}
							addition_list = new ArrayList<User>();
							MemberSearchTask ms_task = new MemberSearchTask();
							ms_task.execute(temp_id_list,1);
						}
					}
				} else if (type.equals("member")) {

					if (obj.get("action").equals("rejectMember")) {
						String reject_mem = obj.getString("member");

						if (reject_mem.equals(myId)) {
							new AlertDialog.Builder(MainActivity.this)
									.setTitle(
											"You have been excluded from the team.")
									.setMessage(
											"When you click on the Confirm button, \nSmartCoworker will be terminated.")
									.setPositiveButton(
											"Confirm",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													// TODO Auto-generated
													// method stub
													finish();
												}
											}).show();
						} else {
							for (int i = 0; i < mem_list.size(); i++) {
								if (mem_list.get(i).getId().equals(reject_mem)) {
									_layout.removeViewAt(i);
									mem_list.remove(i);
									profile_img_factory.remove(mem_list.get(i)
											.getId());
									break;
								}
							}
							renewMemberObj();
						}
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

}